//package pro.shushi.pamirs.middle.lock.zookeeper;
//
//import org.apache.curator.RetryPolicy;
//import org.apache.curator.framework.CuratorFramework;
//import org.apache.curator.framework.CuratorFrameworkFactory;
//import org.apache.curator.framework.recipes.locks.InterProcessMutex;
//import org.apache.curator.framework.state.ConnectionState;
//import org.apache.curator.framework.state.ConnectionStateListener;
//import org.apache.curator.retry.ExponentialBackoffRetry;
//import org.apache.zookeeper.CreateMode;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//
//import java.util.concurrent.TimeUnit;
//
/// **
// * @Description zookeeper分布式锁
// * @Author junwei
// * Date 2019-08-23
// */
//public class CuratorUtils  {
//
//    private static final Logger log = LoggerFactory.getLogger(CuratorUtils.class);
//
//    private static CuratorFramework client;
//
//    private static final String LOCK_PATH = "/lock/";
//
//    private static long lockTimeoutMs = 90000;
//
//    static {
//        String zookeeperAddress = "";
//        RetryPolicy retryPolicy = new ExponentialBackoffRetry(2000, 3);
//        client = CuratorFrameworkFactory.builder().connectString(zookeeperAddress).retryPolicy(retryPolicy)
//                .sessionTimeoutMs(6000).build();
//        client.start();
//    }
//
//    public static InterProcessMutex tryLock(String path, int waitSeconds) {
//        SessionConnectionListener sessionConnectionListener = new SessionConnectionListener(path, waitSeconds);
//        client.getConnectionStateListenable().addListener(sessionConnectionListener);
//        try {
//            InterProcessMutex lock = new InterProcessMutex(client, LOCK_PATH + path);
//            if (lock.acquire(waitSeconds, TimeUnit.SECONDS)) {
//                return lock;
//            }
//
//        } catch (Exception e) {
//            log.error("get zookeeper lock error", e);
//        }
//        return null;
//    }
//
//    public static void releaseLock(InterProcessMutex lock) {
//        if (lock != null && lock.isAcquiredInThisProcess()) {
//            try {
//                lock.release();
//            } catch (Exception e) {
//                log.error("release lock error", e );
//            }
//        }
//    }
//
//   /* public static synchronized Boolean tryLocalLock(String moduleName, String moduleState) {
//        String moduleStateLock = PamirsCacheKit.getModuleStateLock(moduleName);
//        String currentModuleState = fetchStateFromLock(moduleStateLock);
//        if ((ModuleStateEnum.TORELOAD.getValue().equals(currentModuleState)
//                || ModuleStateEnum.TOINSTALL.getValue().equals(currentModuleState)
//                || ModuleStateEnum.TOUPGRADE.getValue().equals(currentModuleState)
//                || ModuleStateEnum.TOPREVIEW.getValue().equals(currentModuleState)
//                || ModuleStateEnum.TOPUBLISH.getValue().equals(currentModuleState)
//                || ModuleStateEnum.TOREMOVE.getValue().equals(currentModuleState))
//                && !isValidLock(moduleStateLock)
//        ) {
//            log.error("{} 未获取本地锁 {}", moduleName, moduleState);
//            return false;
//        }
//        PamirsCacheKit.putModuleStateLock(moduleName, moduleState + MakerConstants.keyVariablePostfix + System.currentTimeMillis());
//        return true;
//    }*/
//
//   /* public static synchronized void releaseLocalLock(String moduleName, String moduleState) {
//        PamirsCacheKit.putModuleStateLock(moduleName, moduleState + MakerConstants.keyVariablePostfix + System.currentTimeMillis());
//    }
//
//    private static String fetchStateFromLock(String lock){
//        if(StringUtils.isBlank(lock)){
//            return null;
//        }
//        String[] lockToken = lock.split("\\"+MakerConstants.keyVariablePostfix);
//        if(lockToken.length != 2){
//            return null;
//        }
//        return lockToken[0];
//    }
//
//    private static boolean isValidLock(String lock){
//        if(StringUtils.isBlank(lock)){
//            return Boolean.FALSE;
//        }
//        String[] lockToken = lock.split("\\"+MakerConstants.keyVariablePostfix);
//        if(lockToken.length != 2){
//            return Boolean.FALSE;
//        }
//        log.error("锁判断time:{}", (System.currentTimeMillis() - new Date(Long.valueOf(lockToken[1])).getTime()) > lockTimeoutMs);
//        return (System.currentTimeMillis() - new Date(Long.valueOf(lockToken[1])).getTime()) > lockTimeoutMs;
//    }
//
//    @PreDestroy
//    public void destory() {
//        client.close();
//    }
//*/
//    /**
//     * 监听，当zk的session失效时，重新连接session并且创建临时节点
//     */
//    static class SessionConnectionListener implements ConnectionStateListener {
//
//        private String path;
//        private int waitSeconds;
//
//        public SessionConnectionListener(String path, int waitSeconds) {
//            this.path = path;
//            this.waitSeconds = waitSeconds;
//        }
//
//        @Override
//        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState){
//            if(connectionState == ConnectionState.LOST) {
////                log.error("zk session超时");
//                while(true) {
//                    try {
//                        if(curatorFramework.getZookeeperClient().blockUntilConnectedOrTimedOut()){
//                            curatorFramework.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath(LOCK_PATH + path);
////                            log.error("{} 重新获取锁成功", path);
//                            break;
//                        }
//                    } catch (InterruptedException e) {
////                        log.error("sessionConnectionListener error", e);
//                        break;
//                    } catch (Exception e){
////                        log.error("sessionConnectionListener error", e);
//                    }
//                }
//            }
//        }
//    }
//}
